package com.baijia.processor;

import com.baijia.dao.OrgAccountDao;
import com.baijia.dao.UserDao;
import com.baijia.dao.po.OrgAccount;
import com.baijia.dao.po.User;
import com.baijia.databus.AbstractProcessor;
import com.baijia.databus.ChangedRow;
import com.baijia.util.SerialNumberUtil;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

/**
 * 监控passport表数据变化 Created by dudu on 16/6/15.
 */
@Component
public class PassportTableProcessor extends AbstractProcessor {

    @Resource
    private UserDao userDao;

    @Resource
    private OrgAccountDao orgAccountDao;

    private static final Logger logger = LoggerFactory.getLogger(PassportTableProcessor.class);

    @Override
    public String topic() {
        return "cdb.passport";
    }

    @Override
    public boolean process(List<ChangedRow> changedRows) {
        if (changedRows != null && changedRows.size() > 0) {
            for (ChangedRow columnChange : changedRows) {
                switch (columnChange.getChangedType()) {
                    case UPDATE:
                        doUpdate(columnChange);
                        break;
                    case DELETE:
                        break;
                    case INSERT:
                        doInsert(columnChange);
                        break;
                    default:
                        break;
                }
            }
        }

        // FIXME 根据操作结果做出返回
        return true;
    }

    private void doInsert(ChangedRow columnChange) {
        Map<String, String> newRecord = columnChange.getNewValue();
        logger.info("passport id = {}", newRecord.get("ID"));
        logger.debug("[Insert][before change]data = {}", columnChange.getOldValue());
        logger.debug("[Insert][after  change]data = {}", newRecord);

        // 向user表同步更新数据
        // syncUser(newRecord);

        // 向机构用户表同步更新数据
        // syncOrgUser(newRecord);
    }

    private void syncOrgUser(Map<String, String> newRecord) {
        OrgAccount o = orgAccountDao.findByMobile(newRecord.get("MOBILE"), newRecord.get("COUNTRY_CODE"));
        if (o != null) {
            logger.warn("user mobile {} is already exist in Org site!", newRecord.get("MOBILE"));
            return;
        }
        OrgAccount orgAccount = new OrgAccount();
        orgAccount.setMobile(newRecord.get("MOBILE"));
        orgAccount.setPassword(newRecord.get("PASSWORD"));
        orgAccount.setUserName(newRecord.get("USERNAME"));
        orgAccount.setEmail(newRecord.get("EMAIL"));
        Long lastInsertId = orgAccountDao.save(orgAccount);
        long number =
            SerialNumberUtil.generateNumberNoSuffix(lastInsertId.intValue(), SerialNumberUtil.MAX) * 10
                + SerialNumberUtil.ORG_SUFFIX;// 8 普通用户 9 机构用户
        orgAccountDao.updateNumber(lastInsertId, number);
    }

    private void syncUser(Map<String, String> newRecord) {
        User u = userDao.getUserByMobile(newRecord.get("MOBILE"));
        if (u != null) {
            logger.warn("user mobile {} is already exist in Main site!", newRecord.get("MOBILE"));
            return;
        }
        User user = new User();
        user.setMobile(newRecord.get("MOBILE"));
        user.setPassword(newRecord.get("PASSWORD"));
        user.setName(newRecord.get("NAME"));
        user.setEmail(newRecord.get("EMAIL"));
        Long lastInsertId = userDao.save(user);
        long number =
            SerialNumberUtil.generateNumberNoSuffix(lastInsertId.intValue(), SerialNumberUtil.MAX) * 10
                + SerialNumberUtil.USER_SUFFIX;// 8 普通用户 9 机构用户
        userDao.updateNumber(lastInsertId, number);
    }

    private void doUpdate(ChangedRow columnChange) {
        Map<String, String> newRecord = columnChange.getNewValue();
        logger.info("passport id = {}", newRecord.get("ID"));
        logger.debug("[update][before change]data = {}", columnChange.getOldValue());
        logger.debug("[update][after  change]data = {}", newRecord);
        // syncUpdateUser(newRecord);
    }

    private void syncUpdateUser(Map<String, String> newRecord) {
        String user_id = newRecord.get("USER_ID");
        if (StringUtils.isBlank(user_id)) {
            logger.warn("sync update user occurs error , user_id is null!");
            return;
        }
        User user = userDao.getById(Long.valueOf(user_id));
        user.setMobile(newRecord.get("MOBILE"));
        user.setPassword(newRecord.get("PASSWORD"));
        user.setName(newRecord.get("NAME"));
        user.setEmail(newRecord.get("EMAIL"));
        user.setMobileVerify(Integer.valueOf(newRecord.get("MOBILE_VERIFY")));
        user.setEmailVerify(Integer.valueOf(newRecord.get("EMAIL_VERIFY")));
        userDao.update(user);
    }
}
